package server.server02;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Date;

public class Response {
    private BufferedWriter bw;
    //正文
    private StringBuilder content;
    //协议头(状态行 请求 回车)信息
    private StringBuilder headerInfo;
    private int len;//正文的字节数
    private final String BLANK = " ";
    private final String CRLF = "\r\n";//换行符
    private Response() {
        content = new StringBuilder();
        headerInfo = new StringBuilder();
        len =0;
    }
    public Response(Socket client) {
        this();
        try {
            bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
        } catch (IOException e) {
            e.printStackTrace();
            headerInfo=null;
        }
    }
    public Response(OutputStream os) {
        this();
        bw = new BufferedWriter(new OutputStreamWriter(os));
    }
    //动态添加内容
    public Response print(String info){
        content.append(info);
        len+=info.getBytes().length;
        return this;
    }
    public Response printIn(String info){
        content.append(info);
        len+=(info+CRLF).getBytes().length;
        return this;
    }

    //推送响应信息
    public void pushBrower(int code) throws IOException {
        if(null==headerInfo){
            code=505;
        }
        createHeadInfo(code);
       bw.append(headerInfo);
       bw.append(content);
       bw.flush();
    }

    //构建头信息
    private void createHeadInfo(int code){
        //1.响应行:HTTP/1.1 200 OK
        headerInfo.append("HTTP/1.1").append(BLANK);
        headerInfo.append(code).append(BLANK);
        switch (code){
            case 200: headerInfo.append("OK").append(CRLF);
            break;
            case 404: headerInfo.append("Not Find").append(CRLF);
            break;
            case 505: headerInfo.append("Server Err").append(CRLF);
                break;
        }
        //2.响应头（最后一行存在空行）
        headerInfo.append("Date:").append(new Date()).append(CRLF);
        headerInfo.append("Server:").append("shsxt Server/0.0.1;charset=GBK").append(CRLF);
        headerInfo.append("Content-type:text/html").append(CRLF);
        headerInfo.append("Content-length:").append(len).append(CRLF);
        headerInfo.append(CRLF);
    }
}
